//
//  Photo.swift
//  FileManager-NSCache-HttpDownload
//
//  Created by DaleGuo on 2023/9/19.
//

import Foundation
import SwiftUI



class PhotoModelDataFileManager {
    static let instance = PhotoModelDataFileManager()
    
    let folderName = "cache_photo"
    
    private init() {
        createFolderNeeded()
    }
    
    private func createFolderNeeded() {
        guard let url = getFolderPath() else {
            return
        }
        
        if !FileManager.default.fileExists(atPath: url.path) {
            do {
                try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
                
                print("______create folder______")
                      
            } catch {
                print("Create Folder ERRER: \(error)")
            }
        }
    }
    
    private func getFolderPath() -> URL? {
        return FileManager
            .default
            .urls(for: .cachesDirectory, in: .userDomainMask)
            .first?
            .appendingPathComponent(folderName)
    }
    
    func getImagePath(key: String) -> URL? {
        guard let folder = getFolderPath() else {
            return nil
        }
        
        return folder.appendingPathComponent(key + ".png")
    }
    
    func add(key: String, value: UIImage) {
        guard
            let data = value.pngData(),
            let url = getImagePath(key: key) // 生成image路径
        else {
            return
        }
        
        do {
            print("Save data in file : url---=  \(url)")
            try data.write(to: url)
        } catch {
            print("Save Data in File ERROR: \(error)")
        }
    }
    
    func get(key: String) -> UIImage? {
        guard
            let url = getImagePath(key: key),
            FileManager.default.fileExists(atPath: url.path)
        else {
            return nil
        }
        
            print("Get data in file : url---=  \(url)")
        
//        print("\n\n\n\n\n")
        print(UIImage(contentsOfFile: url.path) ?? "&*&(*&(*&(&&(&(**(")
        return UIImage(contentsOfFile: url.path)
    }
}
